import axios from "../../utils/request"

export const editPhone = (data: { userId: Number,phoneNumber:string}) => {
  return axios({
    url: `http://localhost:8080/mypage/editProfile`,
    method: "post",
    data
  });
}

export const editSex = (data: { userId: Number,sex:Number}) => {
  return axios({
    url: `http://localhost:8080/mypage/sex`,
    method: "put",
    data
  });
}

export const getUserInfo = (userId:number) =>{
  return axios({
    url: `http://localhost:8080/mypage/phone/${userId}`,
    method: "get"
  });
}

export const getUserBalance = (userId:number) =>{
  return axios({
    url: `http://localhost:8080/mypage/info/balance/${userId}`,
    method: "get"
  });
}

// 更新头像

export const editNickname = (data: { userId: Number,newNickname:string}) => {
  return axios({
    url: `http://localhost:8080/mypage/nickname`,
    method: "put",
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: new URLSearchParams(data as any).toString(),
  });
}

export const updateAvatar = (file: File) => {
  const formData = new FormData();
  formData.append("file", file);

  const storedUser = localStorage.getItem('user');
  if (storedUser) {
    const user = JSON.parse(storedUser).user;
    const token = user.token;
    return axios({
      url: `http://localhost:8080/user/avatar`,
      method: "post",
      headers: {
        'Authorization': token,
        'Content-Type': 'multipart/form-data'
      },
      data: formData
    });
  } else {
    return Promise.reject(new Error('用户未登录'));
  }
};


// 充值请求
export const rechargeBalance = (userId: number, amount: number) => {
    return axios({
      url: `http://localhost:8080/mypage/recharge/${userId}`,
      method: "post",
      data: { amount }
    });
};

// 充值请求
export const deductBalance = (userId: number, amount: number) => {
  return axios({
    url: `http://localhost:8080/mypage/recharge/${userId}`,
    method: "post",
    data: { amount }
  });
};